<template>
  <div class="toast toast-top toast-center">
    <div v-if="msg" class="alert alert-soft" :class="alertClass">
      <span>{{ msg }}</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, watch, onMounted } from "vue";
interface Props {
  status: "success" | "error";
  duration?: number;
}
const props = defineProps<Props>();

const msg = defineModel<string>("msg");

let timer: NodeJS.Timeout | null = null;

watch(msg, (newVal) => {
  if (newVal) {
    initSSR();
  }
});

const initSSR = () => {
  timer && clearTimeout(timer);
  timer = setTimeout(() => {
    msg.value = "";
  }, props.duration || 1500);
};

onMounted(() => {
  initSSR();
});

const alertClass = computed(() => {
  const stauts = props.status || "success";
  return {
    "alert-success": props.status === "success",
    "alert-error": props.status === "error",
  };
});
</script>
